
package base.core.config;



import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import base.core.api.Result;
import base.core.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

/**
 * 统一的异常捕获和返回对象封装
 */
@Slf4j
@Component
@RestControllerAdvice
public class BaseExceptionHandler {
    /**
     * 业务异常
     */
    @ExceptionHandler(BaseException.class)
    public Object handleElegantException(BaseException exception) {

        //发生实际系统异常,打印错误日志,并返回错误日志
        if (exception.getException() != null) {
            log.error("全局异常信息  {}    ex={}", exception.getClass().getSimpleName(), exception.getMessage(), exception);
            return Result.failed().setException(getExceptionStr(exception)).setMsg(exception.getMessage());
        }
        //系统未出现Exception,表示手动终止业务,不发送错误日志
        return Result.failed().setMsg(exception.getMessage());
    }

    /**
     * 全局异常捕获,并直接返回异常给beforeBodyWrite统一处理
     */
    @ExceptionHandler(Exception.class)
    public Object handleGlobalException(Exception exception) {
        log.error("全局异常信息  {}    ex={}", exception.getClass().getSimpleName(), exception.getMessage(), exception);
        return Result.failed().setException(getExceptionStr(exception)).setMsg("错误: 系统处理失败!");
    }

    /**
     * 将异常转成字符串
     */
   private String getExceptionStr(Exception exception) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(exception.getMessage()).append("\n");
        for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
            buffer.append(stackTraceElement.toString()).append("\n");
        }
        return buffer.toString();
    }
}
